<?php

namespace App\Http\Controllers\VideoAdmin;

use App\Http\Config\ErrorCode;
use App\Http\Controllers\Admin\BaseController;
use App\Library\UpTools;
use App\Models\video\BroadcasterModel;
use App\Models\video\BroadcasterRelationModel;
use App\Models\video\PlayClassModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\VideoUserModel;
use App\Models\video\CourseCatalogModel;
use App\Models\video\CourseModel;
use App\Models\video\DynamicModel;
use App\Models\video\PlayListModel;
use App\Models\video\VodApis;
use App\Models\video\VodHandle;
use App\Models\video\VodVideoModel;
use Illuminate\Http\Request;

class BroadcasterController extends BaseController
{
    public function __construct(Request $request){
        parent::__construct($request);
    }

    // 可用的up主列表
    public function getAll(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        $data = BroadcasterModel::getFields("id,name", ["mall_id" => $request->mallData["id"], "status" => 1]);
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // up主列表
    public function getList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        $db = BroadcasterModel::query()->select(["*"])->where("mall_id", $request->mallId);
        if($request->status){
            $db->where('status', "=", $request->status);
        }
        if($request->searchText){
            if(is_numeric($request->searchText)){
                $temp = BroadcasterRelationModel::getFields("broadcaster_id", [["mall_id", "=", $request->mallData['id']], ['mobile', 'like', "%{$request->searchText}%"]], false, false);
                $id = [];
                foreach ($temp as $i){
                    $id[] = $i["broadcasterId"];
                }
                $db->whereIn("id", $id);
            }else {
                $db->where("name", "like", "%{$request->searchText}%");
            }
        }
        $db->with(["relation" => function ($q) {
            $q->leftJoin(VideoUserModel::query()->getModel()->getTable()." as u", "u.id", "=", "up_broadcaster_relation.user_id")
                ->select(["up_broadcaster_relation.mobile", "up_broadcaster_relation.broadcaster_id", "u.nickname"]);
        }]);
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 10;
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data['list'] = $db->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("register_time", "desc")->get();
        if($data['list']){
            $data['list'] = BroadcasterModel::transferField($data['list']->toArray());
            foreach ($data["list"] as &$item){
                $item["managerList"] = [];
                foreach ($item['relation'] as $i){
                    $item["managerList"][] = "{$i["nickname"]}({$i["mobile"]})";
                }
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 添加
    public function add(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request->name)){
            return $this->return_result(ErrorCode::code("params_not_exist", "up主昵称"));
        }
        $data = ["name" => $request->name];
        if(!empty($request->bgImageId)){
            $data["bg_image_id"] = $request->bgImageId;
        }
        if(!empty($request->avatarId)){
            $data["avatar_id"] = $request->avatarId;
        }
        if(!empty($request->desc)){
            $data["desc"] = $request->desc;
        }
        $userData = [];
        if(!empty($request->userId)){
            $userId = explode(",", $request->userId);
            $userData = VideoUserModel::query()->select("id", "mobile", "openid", "nickname")
                ->whereIn("id", $userId)->where("mall_id", $request->mallData["id"])
                ->get()->toArray();
            if(!empty($userData)) {
                $res = BroadcasterRelationModel::query()->select("user_id")
                    ->where("mall_id", $request->mallData["id"])->whereIn("user_id", $userId)
                    ->get()->toArray();
                if(!empty($res)) {
                    $temp = [];
                    $msg = '';
                    foreach ($userData as $a) {
                        $temp[$a["id"]] = $a;
                    }
                    foreach ($res as $value){
                        $msg = isset($temp[$value["user_id"]]) ? $temp[$value["user_id"]]["nickname"]."," : "";
                    }
                    return $this->return_result(ErrorCode::code("customized", "用户 ".substr($msg, 0, strlen($msg)-1)." 已经是UP主了"));
                }
            }
        }
        $id = BroadcasterModel::add($data, true);
        foreach ($userData as $item){
            $relationData = [
                "mobile" => $item["mobile"], "user_id" => $item["id"], "openid" => $item['openid'], 'broadcaster_id' => $id
            ];
            BroadcasterRelationModel::add($relationData);
            VideoUserModel::doUpdate(["user_type" => 1], ["id" => $item["id"]]);
        }
        return $this->return_result($this->returnData);
    }

    // 删除
    public function delete(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "up主ID"));
        }
        $data = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]], true, false);
        if($data["operateMode"] == '1' && BroadcasterModel::getCount(["status" => 1,"mall_id" => $request->mallData["id"]]) < 2){ // 个人模式
            return $this->return_result(ErrorCode::code("customized", "个人模式下无法删除up主"));
        }
        BroadcasterModel::delById($request->id);
        return $this->return_result($this->returnData);
    }

    // 获取up主用户基本信息
    public function getInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $data = BroadcasterModel::with(["relation" => function ($q) use ($request) {
                $q->select(["broadcaster_id", "user_id"]);
            }])->where("mall_id", $request->mallId)->where("id", $request->id)
            ->first();
        if(!empty($data)){
            $this->returnData["data"] = BroadcasterModel::transferField($data->toArray());
            foreach ($this->returnData["data"]['relation'] as $item){
                $this->returnData['data']["userId"][] = $item["userId"];
            }
            unset($this->returnData["data"]['relation']);
        }else{
            $this->returnData["data"] = [];
        }
        return $this->return_result($this->returnData);
    }

    // 更新信息
    public function updateInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::code("params_not_exist", "up主ID"));
        }
        if(empty($request->name)){
            return $this->return_result(ErrorCode::code("params_not_exist", "up主昵称"));
        }
        $data = ["name" => $request->name];
        if(!empty($request->bgImageId)){
            $data["bg_image_id"] = $request->bgImageId;
        }
        if(!empty($request->avatarId)){
            $data["avatar_id"] = $request->avatarId;
        }
        if(!empty($request->desc)){
            $data["desc"] = $request->desc;
        }
        if(!BroadcasterModel::doUpdate($data, ["id" => $request->id])){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '更新失败';
        }
        if(!empty($request->userId)){
            $userId = explode(",", $request->userId);
            $userData = VideoUserModel::query()->select("id", "mobile", "openid", "nickname")
                ->whereIn("id", $userId)->where("mall_id", $request->mallData["id"])
                ->get()->toArray();
            if(!empty($userData)) {
                $temp = $userData;
                $userData = [];
                foreach ($temp as $a) {
                    $userData[$a["id"]] = $a;
                }
                unset($temp);
                $res = BroadcasterRelationModel::query()->select("user_id")
                    ->where("mall_id", $request->mallData["id"])->whereIn("user_id", $userId)
                    ->where("broadcaster_id", "<>", $request->id)
                    ->get()->toArray();
                if(!empty($res)) {
                    $msg = '';
                    foreach ($res as $value){
                        $msg = isset($userData[$value["user_id"]]) ? $userData[$value["user_id"]]["nickname"]."," : "";
                    }
                    return $this->return_result(ErrorCode::code("customized", "用户 ".substr($msg, 0, strlen($msg)-1)." 已经是UP主了"));
                }
                $databaseUser = [];
                $relData = BroadcasterRelationModel::getFields("id,user_id", ["mall_id" => $request->mallData["id"], "broadcaster_id" => $request->id], false, false);
                foreach ($relData as $key => $i){
                    if(!in_array($i["userId"], $userId)){
                        BroadcasterRelationModel::delByFilter(["id" => $i['id']]);
                        VideoUserModel::doUpdate(["user_type" => 0], ["id" => $i["userId"]]);
                    }
                    $databaseUser[] = $i["userId"];
                }
                $relationData = array_diff($userId, $databaseUser);
                foreach ($relationData as $id){
                    BroadcasterRelationModel::add([
                        "mobile" => $userData[$id]["mobile"], "user_id" => $id, "openid" => $userData[$id]['openid'], "broadcaster_id" => $request->id
                    ]);
                }
                VideoUserModel::query()->whereIn("id", $relationData)->update(["user_type" => 1]);
            }
        }
        return $this->return_result($this->returnData);
    }

    public function updateStatus(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $data = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]], true, false);
        if($request->status == '2'){ // 禁用
            if($data["operateMode"] == '1' && BroadcasterModel::getCount(["mall_id" => $request->mallData["id"], "status" => 1]) <= 1){ // 个人模式,关闭其它up主
                return $this->return_result(ErrorCode::code("customized", "个人模式下无法禁用up主"));
            }
            BroadcasterModel::doUpdate(["status" => 2], ["id" => $request->id]);
        }else{ // 启用
            if($data["operateMode"] == '1'){ // 个人模式,关闭其它up主
                BroadcasterModel::doUpdate(["status" => 2], ["mall_id" => $request->mallData["id"]]);
            }
            BroadcasterModel::doUpdate(["status" => 1], ["id" => $request->id]);
        }
        return $this->return_result($this->returnData);
    }

    public function getSign(){
        $settingData = VideoSettingModel::getFields("secret_id,secret_key", ["mall_id" => request()->mallData["id"]]);
        if(empty($settingData["secretId"]) || empty($settingData["secretKey"])){
            throw new \Exception("腾讯云云点播访问密钥未配置");
        }
        $secret_id = $settingData["secretId"];
        $secret_key = $settingData["secretKey"];

        // 确定签名的当前时间和失效时间
        $current = time();
        $expired = $current + 86400;  // 签名有效期：1天

        // 向参数列表填入参数
        $arg_list = array(
            "secretId" => $secret_id,
            "currentTimeStamp" => $current,
            "expireTime" => $expired,
            "random" => rand());

        // 计算签名
        $original = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $original, $secret_key, true).$original);


        $this->returnData["data"] = ["sign" => $signature];
        return $this->return_result($this->returnData);
    }

    // 完善媒体信息
    public function saveMediaInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        $database = VodVideoModel::query()->select("id","vid","video_duration","broadcaster_id","video_url_list","handle_result")
            ->where("id", $request->id)->orWhere("vid", $request->id)->first();
        if(empty($database)){
            $broadcasterData = BroadcasterModel::getFields("id", ["status" => 1, "mall_id" => request()->mallData["id"]], true, false);
            $request->id = VodVideoModel::toAdd(["vid" => $request->id, "media_url" => "", "broadcaster_id" => $broadcasterData["id"], "status" => 0], true);
            $database = VodVideoModel::getFields("id,vid,video_duration,broadcaster_id,video_url_list,handle_result", ["id" => $request->id], true,false);
        }else{
            $database = VodVideoModel::transferField($database->toArray());
            $request->id = $database["id"];
        }
        if(empty($request->title)){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频标题"));
        }
        $data = [
            "title" => mb_substr($request->title, 0, 120), "status" => 1, "pay_mode" => $request->payMode ?: 0, "type" => $request->type ?: 1,
            'cat_id' => $request->catId ?: 0, "desc" => "", "file_type" => $request->fileType ? explode("/", $request->fileType)[0] : ""
        ];
        if(!empty($request->desc)){
            $data["desc"] = mb_substr($request->desc, 0, 300);
        }
        if(!empty($request->coverImgId)){
            $data["cover_img_id"] = $request->coverImgId;
        }
        if(!empty($request->tryTime)){
            $data["try_time"] = $request->tryTime;
        }
        if(!empty($request->payMoney)){
            $data["pay_money"] = $request->payMoney;
        }
        $res = VodApis::getInstance()->modifyMediaInfo($database["vid"], UpTools::transferFields($data));
        if($res["code"] == '0') {
            if($request->payMode == '1'){
                $data["member_mode"] = $request->memberMode ?: '0'; // 会员优惠，0免费，1折扣
            }elseif($request->payMode == '2'){ // 会员免费
                $data["member_mode"] = '0'; // 会员优惠，0免费
            }
            if($abc = VodVideoModel::doUpdate($data, ["id" => $request->id])){
                if($request->operateType == 'add') { // 添加新视频
                    if(!DynamicModel::query()->where(["belong_id" => $request->id, "type" => 2])->count()) { // 发布普通视频
                        DynamicModel::toAdd([
                            "broadcaster_id" => $database["broadcasterId"], "belong_id" => $request->id,
                            "contents" => $request->dynamicText, "type" => 2, "status" => !empty($database["videoUrlList"]) ? 1 : 0
                        ]);
                    }
                    $videoCount = VodVideoModel::query()->where("broadcaster_id", $database["broadcasterId"])->where("handle_result", "<>", 3)->count();
                    BroadcasterModel::doUpdate(["video_count" => $videoCount], ["id" => $database["broadcasterId"]]);
                    if(!empty($database["videoUrlList"])){
                        VodHandle::getInstance()->sendWxTemplate($data, $request->mallData["id"], $database["broadcasterId"]);
                    }
                }
                if ($request->classId) {
                    $res = PlayListModel::query()->select("id", "class_id as classId")
                        ->where(["mall_id" => $request->mallData["id"], "video_id" => $request->id, "broadcaster_id" => $database["broadcasterId"]])
                        ->first();
                    if (!empty($res->id)) {
                        if ($res->classId != $request->classId) {
                            $res = json_decode(json_encode($res), true);
                            PlayListModel::delById($res->id, $res);
                            PlayListModel::toAdd(["broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id, "class_id" => $request->classId]);
                        }
                    } else {
                        PlayListModel::toAdd(["broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id, "class_id" => $request->classId]);
                    }
                }elseif($request->courseId){
                    $res = CourseModel::query()->from(CourseModel::query()->getModel()->getTable()." as c")
                        ->leftJoin(CourseCatalogModel::query()->getModel()->getTable()." as cc", "c.id", "=", "cc.course_id")
                        ->where(["cc.video_id" => $request->id])
                        ->select("cc.course_id")
                        ->first();
                    if(empty($res->course_id)){
                        CourseCatalogModel::toAdd(["course_id" => $request->courseId, "broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id]);
                    }elseif($res->course_id != $request->courseId){
                        CourseCatalogModel::delByFilter(['course_id' => $res->course_id, "video_id" => $request->id]);
                        CourseCatalogModel::toAdd(["course_id" => $request->courseId, "broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id]);
                    }
                }
            }
        }else{
            $this->returnData = $res;
        }
        return $this->return_result($this->returnData);
    }

    // up主的所有播放列表
    public function getAllPlayClass(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $broadcasterData = BroadcasterModel::getFields("id", ["status" => 1, "mall_id" => $request->mallData["id"]], true, false);
        $playClassData = PlayClassModel::getFields("id,name", ["broadcaster_id" => $broadcasterData['id']], false, false);
        if(empty($playClassData)){
            $playClassData = [["id" => 0, "name" => "默认"]];
        }
        $this->returnData["data"] = $playClassData;
        return $this->return_result($this->returnData);
    }
}